package com.ysh.webflux.service.impl;

import com.ysh.webflux.dao.UserRepository;
import com.ysh.webflux.pojo.User;
import com.ysh.webflux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 袁胜虎 on 2022/9/22 22:35
 */
public class UserServiceImpl implements UserService {
    private UserRepository userRepository;

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public Mono<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public void addUser(User user) {
        userRepository.save(user).subscribe();
    }

    @Override
    public Flux<User> findAllUser() {
        return userRepository.findAll();
    }

    @Override
    public Flux<User> findByNameLike(String name) {
        return userRepository.findAllByNameLike(name);
    }

    @Override
    public Mono<User> findByNameEquals(String name) {
        return userRepository.findUserByNameEquals(name);
    }

    @Override
    public Mono<Integer> deleteByNameEquals(String name) {
        return userRepository.deleteUserByNameEquals(name);
    }

    @Override
    public void updateUser(User user) {
        //先查询后更新(git中先pull够push)
        userRepository.findById(user.getUid()).map(user1 -> {
            if (user.getAge() != null) {
                user1.setAge(user.getAge());
            }
            if (user.getAddress() != null) {
                user1.setAddress(user.getAddress());
            }
            if (user.getName() != null) {
                user1.setName(user.getName());
            }
            if (user.getBirthDay() != null) {
                user1.setBirthDay(user.getBirthDay());
            }
            return user1;
        }).subscribe(user1 -> userRepository.updateUserById(user1).subscribe());

    }


    @Override
    public Mono<User> findFirstByNameLike(String name) {
        return userRepository.findFirstByNameLike(name);
    }
}
